<?php

/**
 * Erra_Utils_Tools - Utility class
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Erra_Utils_Tools {

    /**
     * Erra_Utils_Tools::greatCircleDistance() Returns distance in kilometers between two points in latitude/longitude
     *
     * @param mixed $long
     * @param mixed $lat
     * @param mixed $longDest
     * @param mixed $latDest
     * @return
     */
    public static function greatCircleDistance($long, $lat, $longDest, $latDest) {
        if (!is_numeric($longDest) || $longDest == 0 || !is_numeric($latDest) || $latDest == 0 || !is_numeric($long) || $long == 0 || !is_numeric($lat) || $lat == 0) {
            return '?';
        }
        $point1 = array('long' => $long, 'lat' => $lat);
        $point2 = array('long' => $longDest, 'lat' => $latDest);

        $radius = 6378.136; // Earth's radius (kilometers)
        $pi = 3.141592653589793;
        $deg_per_rad = 57.29578; // Number of degrees/radian (for conversion)
        $distance = ($radius * $pi * sqrt(
                        ($point1['lat'] - $point2['lat']) * ($point1['lat'] - $point2['lat']) + cos($point1['lat'] / $deg_per_rad) // Convert these to * cos($point2['lat'] / $deg_per_rad) // radians for cos() * ($point1['long'] - $point2['long']) * ($point1['long'] - $point2['long'])
                ) / 180);
        return (int) $distance; // Returned using the units used for $radius.
    }

    public static function unhtmlspecialchars($string) {
        $string = str_replace('&amp;', '&', $string);
        $string = str_replace('&#039;', '\'', $string);
        $string = str_replace('&quot;', '\"', $string);
        $string = str_replace('&lt;', '<', $string);
        $string = str_replace('&gt;', '>', $string);

        return $string;
    }

    /**
     * Erra_Utils_Tools::toUrlCompliant() Transforms string to url compliant string
     *
     * @param mixed $strIn
     * @return
     */
    public static function toUrlCompliant($strIn) {
        $strIn = html_entity_decode($strIn, ENT_QUOTES, 'UTF-8');
        $strIn = str_replace("'", '-', $strIn);
        $allowed = '/[^a-zA-Z0-9 ]/';
        $strOut = $strIn;
        // strip accents
        $strOut = strip_accents($strIn);
        // only alphanum and spaces allowed
        $strOut = preg_replace($allowed, '', $strOut);
        // swap spaces for _
        $strOut = str_replace(' ', '-', $strOut);
        // for esthetic
        $strOut = str_replace('--', '-', $strOut);
        $strOut = trim($strOut);
        // make lower case for consistancy
        $strOut = strtolower($strOut);

        return $strOut;
    }

    /**
     * Erra_Utils_Tools::sendMail() - Sends a mail with HTML content
     *
     * @param mixed $to
     * @param mixed $from
     * @param mixed $subject
     * @param mixed $message
     * @return
     */
    public static function sendMail($to, $from, $subject, $message) {
        $headers = 'From:  <' . $from . '>' . "\r\n" .
                'MIME-Version: 1.0' . "\r\n" .
                'Content-type: text/html; charset=utf-8' . "\r\n";
        mail($to, $subject, $message, $headers);
    }

    /**
     * Erra_Utils_Tools::sendTemplatedMail() - Sends a mail with HTML content based on a template
     *
     * @param mixed $to
     * @param mixed $from
     * @param mixed $subject
     * @param mixed $message
     * @return
     */
    public static function sendTemplatedMail($to, $template, $placeholders) {
        $headers = 'From: '.Config_GeneralConfigObject::get('mailer_name').' <'.Config_GeneralConfigObject::get('mailer_address').'>' . "\r\n" .
                'MIME-Version: 1.0' . "\r\n" .
                'Content-type: text/html; charset=utf-8' . "\r\n";
        $message = file_get_contents(DOCUMENT_ROOT . '/application/Views/' . $template);
        $message = str_replace(array_keys($placeholders), array_values($placeholders), $message);
        // Extract subject
        $subject = strstr($message, '</subject>', true);
        $message = trim(str_replace('</subject>', '', strstr($message, '</subject>')));
        $subject = str_replace(array('<subject>', '</subject>'), '', $subject);
        return mail($to, $subject, $message, $headers); 
    }

    public static function sendMassMail($list, $subject, $message) {
        $mail = new PHPMailer();
        $mail->FromName = Config_GeneralConfigObject::get('mailer_name');
        $mail->From = Config_GeneralConfigObject::get('mailer_address');

        $mail->IsHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $message;

        $failCount = 0;
        foreach ($list as $email) {
            $mail->AddAddress($email);
            if (!$mail->Send()) {
                $failCount++;
            }
            $mail->ClearAllRecipients();
        }
        return $failCount;
    }

    public static function sendMassSms($userPhones, $message) {
        if (is_array($userPhones) && count($userPhones)) {
            foreach ($userPhones as $userPhone) {
                if (strlen($userPhone) == 10 && is_numeric($userPhone)) {
                    Tools_SmsGatewayObject::send(Config_GeneralConfigObject::get('sms_sendername'), $userPhone, $message);
                }
            }
        }
    }

    /**
     * Erra_Utils_Tools::sendTemplatedSms() - Sends a templated SMS
     *
     * @param mixed $to
     * @param mixed $from
     * @param mixed $subject
     * @param mixed $message
     * @return
     */
    public static function sendTemplatedSms($to, $template, $placeholders) {
        $to = str_replace(' ', '', $to);
        if (strlen($to) == 10) {
            $message = file_get_contents(DOCUMENT_ROOT . '/application/Views/' . $template);
            $message = str_replace(array_keys($placeholders), array_values($placeholders), $message);
            file_put_contents(DOCUMENT_ROOT.'/sms.txt', 'create sms @ '.time().' TO '.$to.'-'.$template."\n", FILE_APPEND);
            //return Tools_SmsGatewayObject::send(Config_GeneralConfigObject::get('sms_sendername'), $to, $message);
        }
    }

    /**
     * Erra_Utils_Tools::message() - Sends back a formatted message depending the type
     *
     * @param mixed $type
     * @param mixed $message
     * @return
     */
    public static function message($type, $message, $sessionId = null) {
        $type = strtolower($type);

        if ($type != 'info' && $type != 'warning' && $type != 'error' && $type != 'success') {
            $type = 'info';
        }
        if (!is_null($sessionId)) {
            Erra_Persistance_Session::set('message__' . $sessionId, '<div class="field_message field_message_' . $type . '" style="width:300px; padding-left:20px;">' . ucfirst($message) . '</div>');
        } else {
            return '<div class="field_message field_message_' . $type . '" style="width:300px; padding-left:20px;">' . ucfirst($message) . '</div>';
        }
    }

    /**
     * Erra_Utils_Tools::arrayFilterStringKeys() Filters an array by returing only non-numerical keys
     *
     * @param mixed $array
     * @return
     */
    public static function arrayFilterStringKeys($array) {
        $result = array();

        foreach ($array as $arrayKey => $arrayValue) {
            if (!is_numeric($arrayKey))
                $result[$arrayKey] = $arrayValue;
        }

        return $result;
    }

    /**
     * Erra_Utils_Tools::getRelativeTime() - mktime function helper
     *
     * @param mixed $day
     * @param mixed $month
     * @param mixed $year
     * @return
     */
    public static function mktime($day, $month, $year) {
        return mktime(0, 0, 0, date("m") + $month, date("d") + $day, date("Y") + $year);
    }

}

?>